<template>
  <div class="app-container">
    <el-dialog title="批量选择" :visible.sync="checkVisible" width="1300px" :append-to-body="false">
      <div class="serach-container">
        <el-form :inline="true" :model="simpleForm" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
          <el-form-item label="VIN">
            <el-input v-model="simpleForm.vin" maxlength="17" placeholder="请输入VIN码" />
          </el-form-item>
          <el-form-item label="大区">
            <el-select v-model="simpleForm.saleRegionName" clearable placeholder="请选择大区" @change="simpleForm.provinceCode = '', complexForm.cityCode = '', $forceUpdate()">
              <el-option v-for="(item, index) in regions" :key="index + '_' + item.bigAreaCode" :label="item.bigAreaName" :value="item.bigAreaCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="省份">
            <el-select v-model="simpleForm.provinceCode" filterable clearable placeholder="请选择省份" @change="complexForm.cityCode = '', $forceUpdate()">
                <el-option v-for="(item, index) in provinceOptions" :key="index + '_' + item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
            </el-select>
          </el-form-item>
           <el-form-item label="店简称">
                <el-input v-model="complexForm.dealerShortName" placeholder="请输入店简称"/>
            </el-form-item>
            <el-form-item label="店代码">
                <el-input v-model="complexForm.dealerCode" placeholder="请输入店代码"/>
            </el-form-item>
            <el-form-item label="车系标准名称">
                <el-select
                    v-model="complexForm.seriesNormalName"
                    filterable
                    clearable
                    placeholder="请选择车系标准名称"
                    @change="(complexForm.modelName = ''), $forceUpdate()"
                >
                    <el-option
                    v-for="item in vehicleOptions"
                    :key="item.seriesNormalName"
                    :label="item.seriesNormalName"
                    :value="item.seriesNormalName"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="车系">
                <el-select
                    v-model="complexForm.seriesName"
                    filterable
                    clearable
                    placeholder="请选择车系"
                    @change="(complexForm.modelName = ''), $forceUpdate()"
                >
                    <el-option
                    v-for="item in vehicleOptions"
                    :key="item.seriesName"
                    :label="item.seriesName"
                    :value="item.seriesName"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="车型">
                <el-select
                    v-model="complexForm.modelName"
                    filterable
                    clearable
                    placeholder="请选择车型"
                    @change="$forceUpdate()"
                >
                    <el-option
                    v-for="item in modelOptios"
                    :key="item.modelName"
                    :label="item.modelName"
                    :value="item.modelName"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="上牌大区">
                <el-select
                    v-model="complexForm.plateBigArea"
                    clearable
                    placeholder="请选择上牌大区"
                    @change="(complexForm.plateCity = ''), $forceUpdate()"
                >
                    <el-option
                    v-for="item in plateRegions"
                    :key="item.bigAreaCode"
                    :label="item.bigAreaName"
                    :value="item.bigAreaCode"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="上牌城市">
                <el-select
                    v-model="complexForm.plateCity"
                    filterable
                    clearable
                    placeholder="请选择上牌城市"
                    @change="$forceUpdate()"
                >
                    <el-option
                    v-for="item in plateCityOptions"
                    :key="item.cityCode"
                    :label="item.cityName"
                    :value="item.cityCode"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="开票日期">
                <el-date-picker
                    v-model="invoiceDate"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
            </el-form-item>
            <el-form-item label="上牌日期">
                <el-date-picker
                    v-model="plateDate"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
            </el-form-item>
            <el-button type="primary" @click="queryTableList">查询</el-button>
            <el-button @click="handelRest">重置</el-button>
        </el-form>
    </div>
    <div class="section-container">
      <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="300" ref="multipleTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-for="item in tables.columns" :key="item.key" :label="item.lable" :width="item.width" :align="item.align" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <span  v-if="item.key === 'effectiveEndTime'" >{{ row.startTime ?  (row.startTime + '至' + row.endTime) : '' }}</span>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="状态" align="center" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column> -->
      </el-table>
      <pagination :total="total" :page.sync="pages.page" :limit.sync="pages.limit" @pagination="changePages" />
      <div class="tips" v-if="multipleSelection.length">
          已选择：<el-tag style="margin: 0 5px 5px 0;" v-for="item in multipleSelection" :key="item.id" closable @close="setSelect(item.id)" type="info">{{ item.vin }}</el-tag>
      </div>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="handleConfirmSelect">确认</el-button>
        <el-button @click="checkVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getStorageByKey, unique_arr_by_key, dateFtt } from '@/utils/public'
import Pagination from '@/components/Pagination'
import { queryList } from '@/api/crossRegionalMonitoring'

export default {
  name: 'DetailDialog',
  components: { Pagination },
  data() {
    return {
      tables: {
        columns: [
          { lable: "VIN", key: "vin", width: "160px", align: "center" },
          {
            lable: "大区",
            key: "saleRegionName",
            width: "80px",
            align: "center"
          },
          { lable: "省份", key: "province", width: "80px", align: "center" },
          { lable: "城市", key: "city", width: "80px", align: "center" },
          {
            lable: "店简称",
            key: "dealerShortName",
            width: "100px",
            align: "center"
          },
          {
            lable: "店代码",
            key: "dealerCode",
            width: "80px",
            align: "center"
          },
          {
            lable: "车系标准名称",
            key: "seriesNormalName",
            width: "160px",
            align: "center"
          },
          { lable: "车系", key: "seriesName", width: "120px", align: "center" },
          { lable: "车型", key: "modelName", width: "160px", align: "center" },
          {
            lable: "上牌人姓名",
            key: "plateName",
            width: "90px",
            align: "center"
          },
          {
            lable: "上牌大区",
            key: "plateBigArea",
            width: "80px",
            align: "center"
          },
          {
            lable: "上牌省份",
            key: "plateProvince",
            width: "80px",
            align: "center"
          },
          {
            lable: "上牌城市",
            key: "plateCity",
            width: "80px",
            align: "center"
          },
          {
            lable: "上牌日期",
            key: "plateDate",
            width: "150px",
            align: "center"
          },
          {
            lable: "开票日期",
            key: "invoiceDate",
            width: "90px",
            align: "center"
          }
        ],
        data: []
      },
      pages: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      checkVisible: false,
      simpleForm: {},
      complexForm: {},
      invoiceDate: [],
      plateDate: [],
      multipleSelection: [],
       // 大区数据
      regions: getStorageByKey("regionsMap"),
      // 上牌大区数据
      plateRegions: getStorageByKey("regionsMap"),
      // 车系车型数据集
      vehicleOptions: getStorageByKey("vehicleMap"),
      cancelRow: null
    }
  },
  computed: {
    // 省份下拉选项 跟随所选大区而变化
    provinceOptions() {
      if (this.regions && this.regions.length) {
        const currentBigArea = this.regions.filter(
          (item) => this.simpleForm.saleRegionName === item.bigAreaCode
        );
        const allProvince = this.regions.reduce((newArr, current) => {
          return newArr.concat(current.provinceList);
        }, []);
        if (currentBigArea.length)
          return unique_arr_by_key(
            "provinceCode",
            currentBigArea[0].provinceList
          );
        return unique_arr_by_key("provinceCode", allProvince);
      } else {
        return [];
      }
    },
    // 城市下拉选项 跟随所选省份而变化
    cityOptions() {
      const currentProvince = this.provinceOptions.filter(
        (item) => this.simpleForm.provinceCode === item.provinceCode
      );
      if (currentProvince.length) return currentProvince[0].cityDtoList;
      const allCity = this.provinceOptions.reduce((newArr, current) => {
        return newArr.concat(current.cityDtoList);
      }, []);
      return allCity;
    },
    // 上牌城市下拉选项 跟随上牌大区而变化
    plateCityOptions() {
      if (this.plateRegions && this.plateRegions.length) {
        // 获得所有城市列表
        const allCity = this.plateRegions.reduce((newArr, current) => {
          return newArr.concat(
            current.provinceList.reduce((newCityArr, currentProvince) => {
              return newCityArr.concat(currentProvince.cityDtoList);
            }, [])
          );
        }, []);
        // 获取所选大区下的城市
        const plateBigArea = this.complexForm.plateBigArea;
        const currentarea_next_province = this.plateRegions.filter(
          (item) => item.bigAreaCode === plateBigArea
        );
        console.log(currentarea_next_province);
        if (currentarea_next_province.length) {
          return currentarea_next_province[0].provinceList.reduce(
            (newArr, current) => {
              return newArr.concat(current.cityDtoList);
            },
            []
          );
        } else {
          return allCity;
        }
      } else {
        return [];
      }
      // return allCity
    },
    // 车型下拉选项，跟随车系而变化
    modelOptios() {
      if (this.vehicleOptions && this.vehicleOptions.length) {
        const { seriesName, seriesNormalName } = this.complexForm;
        const allModel = this.vehicleOptions.reduce((newArr, current) => {
          return newArr.concat(current.modelNameList);
        }, []);
        const currentModelList = this.vehicleOptions.filter(
          (item) =>
            item.seriesName === seriesName ||
            item.seriesNormalName === seriesNormalName
        );
        console.log(currentModelList);
        if (currentModelList.length) return currentModelList[0].modelNameList;
        return allModel;
      } else {
        return [];
      }
    },
  },
  created() {
    this.queryTableList()
  },
  mounted() {
    
  },
  methods: {
    changePages(params) {
      this.pages = { ...params }
      this.queryTableList()
    },
    async queryTableList() {
      this.formatParams();
      this.listLoading = true;
      const { data } = await queryList(this.formatParams());
      const items = data.data;
      this.tables.data = items.list;
      this.total = items.total;
      this.listLoading = false;
    },
    formatParams() {
      const params = { ...this.simpleForm, ...this.complexForm, ...this.pages }
      const saleRegionName = this.simpleForm.saleRegionName;
      // 将大区代码转换成对应名称
      if (saleRegionName) {
        const target = this.regions.find(
          (item) => item.bigAreaCode === saleRegionName
        );
        params["saleRegionName"] = target.bigAreaName;
      }
      if (this.invoiceDate && this.invoiceDate.length) {
        params["invoiceDateStart"] = dateFtt(this.invoiceDate[0]);
        params["invoiceDateEnd"] =
          dateFtt(this.invoiceDate[1], "yyyy-MM-dd") + " 23:59:59";
      }
      if (this.plateDate && this.plateDate.length) {
        params["plateDateStart"] = dateFtt(this.plateDate[0]);
        params["plateDateEnd"] =
          dateFtt(this.plateDate[1], "yyyy-MM-dd") + " 23:59:59";
      }
      return params
    },
      // 清空查询条件
    handelRest() {
      for (const key in this.simpleForm) {
        this.simpleForm[key] = ''
      }
      for (const key in this.complexForm) {
        this.complexForm[key] = ''
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    setSelect(id) {
        this.tables.data.forEach(item => {
            if (item.id === id) {
                this.cancelRow = item
                this.$refs.multipleTable.toggleRowSelection(this.cancelRow, false);
            }
        })
    },
    handleConfirmSelect() {
        if (!this.multipleSelection.length) {
            return this.$message.error('请至少选择一辆车')
        }
        const vins = this.multipleSelection.map(item => (
            item.vin
        ))
        this.$emit('setSelectVin', vins)
        this.checkVisible = false
    }
  }
}
</script>
<style scoped>
  ::v-deep .el-dialog__body{
    padding: 0px;
  }
</style>
<style lang="scss" scoped>
.dialog-container {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  .form{
    width: 35%;
  }
  .map{
    width: 63%;
    box-sizing: border-box;
    height: 300px;
    margin: auto;
  }
  .dialog-footer{
    border-top: 1px solid #e8e8e8;
  }
}
</style>
